package com.medical.auth.service;

import cn.dev33.satoken.stp.SaLoginModel;
import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.extra.servlet.JakartaServletUtil;
import cn.hutool.extra.spring.SpringUtil;
import cn.hutool.http.useragent.UserAgent;
import cn.hutool.http.useragent.UserAgentUtil;
import com.medical.log.event.LoginInforEvent;
import com.medical.core.utils.RequestUtil;
import com.medical.core.utils.ip.AddressUtil;
import com.medical.satoken.constant.SaTokenConstant;
import com.medical.system.model.entity.SysUserOnline;
import jakarta.servlet.http.HttpServletRequest;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

/**
 * 处理用户行为
 */
@Slf4j
@RequiredArgsConstructor
@Service
public class BehaviorService {

    /**
     * 记录用户登录信息
     * @param username
     * @param status
     * @param message
     */
    public void recordLoginInfo(String username, String status, String message) {
        LoginInforEvent loginInforEvent = new LoginInforEvent();
        loginInforEvent.setUsername(username);
        loginInforEvent.setStatus(status);
        loginInforEvent.setMessage(message);
        SpringUtil.publishEvent(loginInforEvent);
    }

    /**
     * 用户在线状态
     */
    public void userOnline(String loginType, Object loginId, String tokenValue, SaLoginModel loginModel) {
        HttpServletRequest request = RequestUtil.getRequest();
        final UserAgent userAgent = UserAgentUtil.parse(request.getHeader("User-Agent"));
        String ip = JakartaServletUtil.getClientIP(request);
        String address = AddressUtil.getRealAddressByIP(ip);

        SysUserOnline userOnline = new SysUserOnline();
        userOnline.setUserName((String)loginModel.getExtra(SaTokenConstant.USER_NAME_KEY));
        userOnline.setBrowser(userAgent.getBrowser().getName());
        userOnline.setIpaddr(ip);
        userOnline.setLoginLocation(address);
        userOnline.setTokenId(tokenValue);
        StpUtil.getTokenSession().set(SaTokenConstant.USER_ONLINE, userOnline);
    }
}
